<?php

namespace app\common\models;

class Coin extends BaseModel
{
    public function getCoin($user_id)
    {
        $coin = $this->getField(['user_id'=>$user_id], 'coin');
        return floatval($coin);
    }

    public function compare($user_id, $coin)
    {
        $old_coin = $this->getCoin($user_id);
        if ($old_coin >= $coin){
            return true;
        }
        return false;
    }

    public function coinInc($user_id = 0, $money = 0, $value = 'money', $memo = '')
    {
        return $this->setCoin($user_id, $money, $value, $memo, 1);
    }

    public function coinDec($user_id = 0, $money = 0, $value = 'money', $memo = '')
    {
        return $this->setCoin($user_id, $money, $value, $memo,2);
    }

    protected function setCoin($user_id, $alter, $value, $memo, $type = 1)
    {
        if (empty($user_id) || empty($alter) || empty($value)) return false;
        $this->startTrans();
        try {
            $before = $this->where('user_id', $user_id)->lock(true)->value($value);
            if ($type == 1){
                $after = $before + floatval(round($alter, 2));
            }else{
                $after = $before - floatval(round($alter, 2));
            }
            $rows = $this->where('user_id', $user_id)->update([$value=>$after]);
            if (!$rows){
                $this->rollback();
                return false;
            }
            // 记录平台币变更记录
            // TODO::后续优化补充
            /*$save_data = [
                'user_id'=>$user_id,
                'alter'=>$alter,
                'before'=>$before,
                'after'=>$after,
                'memo'=>$memo,
                'create_time'=>NEW_TIME,
            ];
            $coin_log = new UserCoinLog();
            $rows = $coin_log->insert($save_data);
            if (!$rows){
                $this->rollback();
                return false;
            }*/
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            return false;
        }
    }
}